/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Raytracing;

import processing.core.PVector;

/**
 *
 * @author Matt
 */
public class FresnelDielectric extends Fresnel{
    
    
    
    public float etai;
    public float etat;
    
    
    public FresnelDielectric(float etai, float etat){
        this.etai = etai;
        this.etat = etat;
    }

    public PVector getFresnel(float cosi) {
        if (cosi < -1.f) {
            cosi = -1.f;
        }
        if (cosi > 1.f) {
            cosi = 1.f;
        }

        boolean entering = false;

        if (cosi > 0) {
            entering = true;
        }
        float ei = etai;
        float et = etat;

        if (entering == false) {
            ei = etat;
            et = etai;
        }

        float sint = ei / et * (float) (Math.sqrt(Math.max(0, 1.f - cosi * cosi)));

        if (sint > 1) {
            return new PVector(1, 1, 1);
        } else {
            float cost = (float) (Math.sqrt(Math.max(0, 1.f - sint * sint)));
            float die = frDiel(Math.abs(cosi), cost, ei, et);
            return new PVector(die, die, die);
        }


    }

    private float frDiel(float cosi, float cost, float ei, float et) {
        float rparl = ((et * cosi) - (ei * cost))
                / ((et * cosi) + (ei * cost));
        float rperp = ((ei * cosi) - (et * cost))
                / ((ei * cosi) + (et * cost));
        return (rparl * rparl + rperp * rperp) / 2.f;


    }
}
